<template>
	<view class="page-container" :class="isIos ? 'paddingBottom' : ''">
		<view class="content-area">
			<view class="galaxy-brand-page">
				<view class="container" :style="{ 'padding-top': statusBarHeight + 'px', }">
					<!-- 顶部banner轮播图 -->
					<swiper class="banner" circular autoplay interval="3000" duration="500"
						indicator-color="rgba(255, 255, 255, 0.4)" indicator-active-color="#fff">
						<swiper-item v-for="(item, index) in bannerList" :key="index" class="swiper-item"
							@click="jumpToMap(item)">
							<image class="banner-image" :src="item.image" mode="aspectFill"></image>
						</swiper-item>
					</swiper>

					<!-- 搜索框 -->
					<view class="search-container">
						<view class="search-box">
							<image class="search-icon" src="/static/search_icon.png" />
							<input class="search-input" v-model="searchValue" placeholder="搜索智能体" confirm-type="search"
								@input="onInputChange" @confirm="handleSearch" />
							<image v-if="searchValue" class="clear-icon" src="/static/clear.png" @click="clearSearch" />
						</view>
					</view>

					<!-- 分类标签 -->
					<view class="category-section">
						<view class="category-item">热门智能体</view>
						<view class="category-tips">更多智能体请查收</view>
					</view>

					<!-- 瀑布流列表 -->
					<waterfall-flow :list="itemList" :column-count="2" :column-width="'344rpx'" :column-gap="20"
						@loadmore="loadMore" :loading="loading" :finished="finished">
						<template #item="{ item }">
							<view class="item-card" @click="toMap(item)">
								<!-- 图片懒加载 -->
								<view class="image-container">
									<view class="item-image"
										:style="{ backgroundImage: `url(${item.image || '/static/default_avatar.png'})` }"
										:class="{ 'loaded': item.imageLoaded }">
									</view>
									<!-- 隐藏的image标签用于监听加载事件 -->
									<image class="hidden-image" :src="item.image || '/static/default_avatar.png'"
										@load="imageLoaded(item.id)" @error="imageError(item.id)">
									</image>
									<!-- 加载动画 -->
									<view class="item-img-loading" v-if="!item.imageLoaded">
										<view class="loading-spinner"></view>
									</view>
									<!-- 骨架屏占位符 -->
									<view class="item-img-skeleton" v-if="!item.imageLoaded">
										<view class="skeleton-shimmer"></view>
									</view>
								</view>
								<view class="item-info">
									<text class="item-title">{{ item.title }}</text>
									<text class="item-desc">{{ item.description }}</text>
								</view>
							</view>
						</template>
					</waterfall-flow>

					<!-- 底部加载更多 -->
					<view class="loading-more" v-if="loading && !finished">
						<!-- <c-lottie src="/static/loading.json" :autoPlay="true" :loop="true" width="100%" height="207rpx" /> -->
					</view>
					<view class="no-more" v-if="finished">
						<text>没有更多数据了</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import WaterfallFlow from "@/components/waterfall-flow/waterfall-flow.vue"
import AppTabbar from "@/components/tabbar/index.vue"
export default {
	components: {
		WaterfallFlow,
		AppTabbar,
	},
	data() {
		return {
			// 自定义底栏对应页面的加载情况
			bannerList: [], // 初始化为空，后续接口获取
			categories: ["更多智能体"],
			currentCategory: "更多智能体",
			itemList: [],
			page: 1,
			pageSize: 10,
			loading: false,
			finished: false,
			navHeight: "", //整体顶部导航栏的高度
			statusBarHeight: "", //状态栏高度
			searchValue: '',
			userDetail: null, // 用于存储用户信息
			isIos: false,
		}
	},
	created() {
		let {
			statusBarHeight,
			system
		} = uni.getSystemInfoSync();
		this.statusBarHeight = statusBarHeight;
		this.isIos = system.indexOf("iOS") > -1
		this.navHeight = statusBarHeight + (system.indexOf("iOS") > -1 ? 44 : 48);
		this.getBannerList();
		this.loadData();
	},
	onReachBottom() {
		if (!this.loading && !this.finished) {
			this.loadMore()
		}
	},
	methods: {
		// 导航页面滚动到底部
		tabbarPageScrollLower(e) { },
		loadData() {
			if (this.loading) return; // 防止重复加载
			this.loading = true;

			this.$Request.getApi('/bot/api/getagentlist', {
				page: this.page - 1,
				search_key: this.searchValue || ''
			}).then(res => {
				if (res && res.status === 1 && Array.isArray(res.data)) {
					const newItems = res.data.map(item => ({
						id: item.id,
						title: item.title,
						description: item.company_name || '', // 适配简介
						image: item.headimgurl || '', // 适配图片
						app_secret: item.app_secret,
						loading: true,
						imageLoaded: false // 添加图片加载状态
					}));

					this.itemList.push(...newItems);

					// 判断是否还有更多
					if (newItems.length < this.pageSize) {
						this.finished = true;
					}
					// 成功加载后才递增页码
					this.page++;
				} else {
					// 接口返回非预期格式，不标记为 finished
					console.warn('接口返回格式异常:', res);
					this.finished = false;
				}
			}).catch(err => {
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				});
				this.finished = true;
				// 上报错误日志
				console.error('加载数据失败:', err);
			}).finally(() => {
				this.loading = false;
			});
		},

		// 加载更多
		loadMore() {
			if (!this.loading && !this.finished) {
				this.loadData()
			}
		},
		toMap(item) {
			// 获取 app_secret
			const appSecret = item.app_secret;
			// 获取缓存中的 userid
			let userInfo = uni.getStorageSync('userInfo');
			const userid = userInfo?.data?.userid || userInfo?.userid || '';
			// 跳转
			uni.navigateTo({
				url: `/activityPages/reserve?appSecret=${encodeURIComponent(appSecret)}&userid=${encodeURIComponent(userid)}`
			});
		},

		// 图片加载完成
		imageLoaded(id) {
			const index = this.itemList.findIndex((item) => item.id === id)
			if (index !== -1) {
				this.$set(this.itemList[index], "loading", false)
				this.$set(this.itemList[index], "imageLoaded", true)
			}
		},

		// 图片加载失败
		imageError(id) {
			const index = this.itemList.findIndex((item) => item.id === id)
			if (index !== -1) {
				this.$set(this.itemList[index], "loading", false)
				this.$set(this.itemList[index], "imageLoaded", true) // 加载失败也设置为已加载，避免无限加载
				// this.$set(this.itemList[index], "image", "/static/images/error.png")
			}
		},

		// 搜索处理
		handleSearch(e) {
			this.searchValue = e.detail.value;
			this.page = 1;
			this.itemList = [];
			this.finished = false;
			this.loadData();
		},
		clearSearch() {
			this.searchValue = '';
			this.page = 1;
			this.itemList = [];
			this.finished = false;
			this.loadData();
		},

		onInputChange(e) {
			this.searchValue = e.detail.value;
			this.page = 1;
			this.itemList = [];
			this.finished = false;
			this.loadData();
		},

		// 获取banner轮播图数据
		getBannerList() {
			this.$Request.getApi('/bot/api/agentcgetad')
				.then(res => {
					if (res && res.status === 1 && Array.isArray(res.data)) {
						// 映射headimgurl为image字段
						this.bannerList = res.data.map(item => ({
							image: item.headimgurl,
							app_secret: item.appsecret,
							id: item.id
						}))
					} else {
						this.bannerList = [];
					}
				})
				.catch(() => {
					this.bannerList = [];
				})
		},
		jumpToMap(item) {
			// // 获取 app_secret
			// const appSecret = item.app_secret;
			// // 获取缓存中的 userid
			// let userInfo = uni.getStorageSync('userInfo');
			// const userid = userInfo?.data?.userid || userInfo?.userid || '';
			// // 跳转
			// uni.navigateTo({
			// 	url: `/activityPages/reserve?appSecret=${encodeURIComponent(appSecret)}&userid=${encodeURIComponent(userid)}`
			// });
			uni.navigateTo({
				url: '/minePages/personalized'
			});
		},

	},
}
</script>

<style lang="scss" scoped>
.webIos {
	::v-deep .tn-tabbar__content__item {
		height: 100%;
	}
}

.webAndroid {
	::v-deep .tn-tabbar__content__item {
		height: auto;
	}
}

.page-container {
	height: 100vh;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

.paddingBottom {
	padding-bottom: 50px;
}

.content-area {
	flex: 1;
	position: relative;
	overflow: hidden;
}

.galaxy-brand-page {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	overflow-y: auto;
	-webkit-overflow-scrolling: touch;
}

.container {
	background-color: #000;
}

// 顶部banner
.banner {
	position: relative;
	width: 100%;
	height: 250rpx;
	overflow: hidden;
	margin: 20px 0;

	.swiper-item {
		display: flex;
		align-items: center;
	}

	.banner-image {
		width: calc(100% - 20px);
		height: 250rpx;
		border-radius: 15rpx 15rpx;
		margin: 0 auto;
	}

	.banner-text {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.banner-title {
			font-size: 24px;
			color: #fff;
			font-weight: bold;
			text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
		}

		.banner-subtitle {
			font-size: 14px;
			color: #fff;
			margin-top: 10px;
			text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
		}
	}
}

// 搜索框
.search-container {
	padding: 0 10px;
	margin-bottom: 20px;

	.search-box {
		display: flex;
		align-items: center;
		background-color: rgba(255, 255, 255, 0.1);
		border-radius: 20px;
		padding: 8px 15px;

		.search-icon {
			width: 38rpx;
			height: 38rpx;
			margin-right: 10rpx;
		}

		.search-input {
			flex: 1;
			height: 24px;
			line-height: 24px;
			font-size: 14px;
			color: #fff;
		}

		.clear-icon {
			width: 29rpx;
			height: 29rpx;
			margin-left: 10rpx;
		}
	}
}

// 分类标签
.category-section {
	padding: 0 10px;
	margin-bottom: 20px;
	display: flex;
	align-items: flex-end;

	.category-item {
		font-size: 31rpx;
		color: rgb(247, 245, 248);
	}

	.category-tips {
		margin-left: 20rpx;
		font-size: 23rpx;
		color: #8C8A8A;
	}
}

// 瀑布流列表
.item-card {
	background-color: #1a1a1a;
	border-radius: 12px;
	overflow: hidden;
	margin-bottom: 15px;

	.image-container {
		position: relative;
		width: 100%;

		.item-image {
			width: 344rpx;
			height: 353.85rpx;
			background: #32322d;
			background-size: cover;
			background-position: top center;
			border-top-left-radius: 18rpx;
			border-top-right-radius: 18rpx;
			opacity: 0;
			transition: opacity 0.3s ease-in-out;

			&.loaded {
				opacity: 1;
			}
		}

		.hidden-image {
			position: absolute;
			top: -9999px;
			left: -9999px;
			width: 1px;
			height: 1px;
			opacity: 0;
			pointer-events: none;
		}

		.item-image-bg {
			width: 344rpx;
			height: 418rpx;
			background-size: cover;
			background-position: top center;
			border-top-left-radius: 12px;
			border-top-right-radius: 12px;
		}

		.c-lottie-warp {
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
		}

		.item-img-loading {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background: #292827;
			border-top-left-radius: 12px;
			border-top-right-radius: 12px;
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1;
			transition: opacity 0.3s ease-in-out;
		}

		.loading-spinner {
			width: 50rpx;
			height: 50rpx;
			border: 3rpx solid rgba(0, 123, 255, 0.2);
			border-top: 3rpx solid #007bff;
			border-radius: 50%;
			animation: spin 1s linear infinite;
			box-shadow: 0 0 20rpx rgba(0, 123, 255, 0.3);
		}

		@keyframes spin {
			0% {
				transform: rotate(0deg);
				opacity: 0.8;
			}

			50% {
				opacity: 1;
			}

			100% {
				transform: rotate(360deg);
				opacity: 0.8;
			}
		}

		.item-img-skeleton {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background: #292827;
			background-size: 200% 100%;
			border-top-left-radius: 12px;
			border-top-right-radius: 12px;
			animation: shimmer 1.5s infinite;
			z-index: 0;
		}

		.skeleton-shimmer {
			width: 100%;
			height: 100%;
			background: inherit;
		}

		@keyframes shimmer {
			0% {
				background-position: -200% 0;
			}

			100% {
				background-position: 200% 0;
			}
		}
	}

	.item-info {
		padding: 10px;
		display: flex;
		flex-direction: column;

		.item-title {
			font-size: 27rpx; // 标题
			font-weight: 500; // 标题
			color: rgba(219, 218, 220, 0.85); // 标题
			margin-bottom: 5px;
		}

		.item-desc {
			font-size: 23rpx; // 简介
			color: #8c8a8a; // 简介
			line-height: 1.4;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 1;
			-webkit-box-orient: vertical;
		}
	}
}

// 加载更多
.loading-more,
.no-more {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 20px 0;
	margin-bottom: 44px;

	text {
		font-size: 14px;
		color: #999;
		margin-top: 10px;
	}
}

html[android]::v-deep .tn-tabbar__content__item__text {
	line-height: 40px !important;
}
</style>